package com.nowcoder.controller;


import com.nowcoder.annotation.LoginRequired;
import com.nowcoder.entity.User;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.HostHolder;
import com.nowcoder.utils.NowCoderUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import sun.security.util.Password;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author cd
 * @since 2021-12-17
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Value("${nowcoder.path.upload}")
    private String uploadPath;

    @Value("${nowcoder.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    @LoginRequired
    @PostMapping("/upload")
    public String uploadAvatar(MultipartFile avatar, Model model) {
        if (avatar == null) {
            model.addAttribute("error", "您还没有选择图片");
            return "/site/setting";
        }

        String filename = avatar.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }

        filename = NowCoderUtil.generateUUID() + suffix;
        String projectPath = System.getProperty("user.dir");
        String path = projectPath + uploadPath + "/" + filename;
        System.out.println(path);
        File dest = new File(path);
        try {
            avatar.transferTo(dest);
        } catch (IOException exception) {
            exception.printStackTrace();
            System.out.println("上传文件失败");
            throw new RuntimeException("上传文件失败");
        }

        //更新头像路径
        //http://localhost:8080/nowcoder/user/avatar/**.png
        User user = hostHolder.getUser();
        String avatarUrl = domain + contextPath + "/user/avatar/" + filename;
        userService.updateAvatar(user.getUid(), avatarUrl);

        return "/redirect:/index";
    }

    @GetMapping("/avatar/{filename}")
    public void getAvatar(@PathVariable("filename") String filename, HttpServletResponse response) {
        String projectPath = System.getProperty("user.dir");
        filename = projectPath + uploadPath + "/" + filename;
        //获取文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        response.setContentType("image/" + suffix);
        try (
            ServletOutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(filename);
        ) {
            byte[] buffer = new byte[1024];
            int i = 0;
            while ((i = fis.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }
        } catch (IOException exception) {
            exception.printStackTrace();
            System.out.println("读取头像失败");
        }

    }

    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword, String newPassword, Model model) {
        User user = hostHolder.getUser();
        Map<String, Object> map = userService.updatePassword(user.getUid(), oldPassword, newPassword);
        if (map == null || map.isEmpty()) {
            return "redirect:/logout";
        } else {
            model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            return "/site/setting";
        }
    }
}

